package swagger2.handler;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import swagger2.domain.AuthAPI;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;

@Aspect
@Component
public class TokenAspect
{

	public static final String TOKEN_NAME = "x-token";

	private static Logger logger = LoggerFactory.getLogger(TokenAspect.class);

	@Pointcut(value = "execution(* swagger2.web.*.*(..))")
	public void packageAspect()
	{
	}

	@Pointcut("@annotation(org.springframework.web.bind.annotation.RequestMapping)")
	public void annoAspect()
	{
	}

	@Around("packageAspect() && annoAspect()")
	public Object execute(ProceedingJoinPoint pjp)
		throws Throwable
	{
		// 从切点上获取目标方法
		MethodSignature methodSignature = (MethodSignature)pjp.getSignature();
		Method method = methodSignature.getMethod();

		if (method.getDeclaringClass().isAnnotationPresent(AuthAPI.class))
		{
			// 如果api需要token认证
			// 从 request header 中获取当前 token
			HttpServletRequest request =
				((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
			String token = request.getHeader(TOKEN_NAME);
			logger.info("{} invoke --> {}", token, method);
			if (StringUtils.isEmpty(token))
			{
				throw new TokenException(TOKEN_NAME + "参数不能为空");
			}
		}
		return pjp.proceed();
	}
}
